package com.sxw.hw_student.system.controller;

import com.sxw.hw_student.system.entity.Student;
import com.sxw.hw_student.system.service.IStudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
 * <p>学生信息控制器</p>
 */
@RestController
@RequestMapping("/student")
public class StudentController {

    @Autowired
    private IStudentService studentService;

    /** 查询所有学生 */
    @GetMapping("/list")
    public List<Student> listStudents() {
        return studentService.list();
    }


    /** 更新学生 */
    @PutMapping("/{studentNo}")
    public boolean updateStudent(@PathVariable String studentNo, @RequestBody Student student) {
        student.setStudentNo(studentNo);  // 设置 studentNo
        return studentService.updateById(student);
    }

    /** 删除学生 */
    @DeleteMapping("/{id}")
    public boolean deleteStudent(@PathVariable Long id) {
        return studentService.removeById(id);
    }
    @PostMapping
    @ResponseBody
    public ResponseEntity<?> addStudent(@RequestBody Student student) {
        try {
            boolean isSaved = studentService.save(student);
            if (isSaved) {
                return ResponseEntity.ok().body(Map.of(
                        "success", true,
                        "message", "学生添加成功"
                ));
            } else {
                return ResponseEntity.badRequest().body(Map.of(
                        "success", false,
                        "message", "添加学生失败"
                ));
            }
        } catch (Exception e) {
            return ResponseEntity.internalServerError().body(Map.of(
                    "success", false,
                    "message", "服务器错误: " + e.getMessage()
            ));
        }
    }
}

